<template>
  <div class="base_info" id="re_tree">
    <span :style="{ color: theme }">{{ title }}</span>
    <div class="head-container" style="margin-top: 10px">
      <el-input v-model="course_value" placeholder="查找" clearable size="small" prefix-icon="el-icon-search"
        style="margin-bottom: 20px" />
    </div>
    <div class="head-container">
      <el-tree :data="courseOptions" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
        @node-click="handleNodeClick" />
    </div>
  </div>
</template>

<script>
import { categoryTree, categoryDetail, categoryList } from "@/api/vadmin/course/course";
import { mapGetters, mapState } from "vuex";

export default {
  name: "CourseTree",
  props: ["title", "value"],

  data() {
    return {
      courseOptions: [],
      course_value: "",
      courseId: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  watch: {
    course_value(newValue) {
      // this.$refs.tree.filter(newValue);
      if (newValue == "") {
        this.$emit("search", "");
      }
    },
    // value(newVal) {
    //   this.course_value = newVal

    //   console.log()
    // }
    // courseId(newValue) {
    //   this.$emit("search", newValue);
    //   // console.log("监听", newValue);
    // },
    // course_value: {
    //   handler: function (newValue) {
    //     // console.log(1, newValue)
    //     this.course_value = newValue;
    //   },
    //   immediate: true,
    // },
  },
  created() {
    // console.log("父亲", this.value)
    this.getTreeselect();
  },
  methods: {
    /** 查询下拉树结构 */
    getTreeselect() {
      categoryList().then((response) => {
        if (response) {
          try {
            // 确保response包含results字段，否则直接使用response
           
            const data = response.results || response;
            if (Array.isArray(data)) {
              this.courseOptions = this.handleTree(data, "id");
            } else {
              console.warn("API返回的数据不是数组:", data);
              this.courseOptions = [];
            }
          } catch (error) {
            console.error("处理树形数据失败:", error);
            this.courseOptions = [];
          }
        } else {
          this.courseOptions = [];
        }
      }).catch(error => {
        console.error("获取分类列表失败:", error);
        this.courseOptions = [];
      });
    },
    getTreeDetail(id) {
      categoryDetail(id).then((res) => {
        if (res) {
        this.courseOptions = res;
        } else {
          this.courseOptions = [];
        }
      }).catch(error => {
        console.error("获取分类详情失败:", error);
        this.courseOptions = [];
      });
    },
    // 处理树形结构数据
    handleTree(data, id, parentId, children) {
      if (!Array.isArray(data)) {
        console.warn("传入handleTree的数据不是数组");
        return [];
      }
      
      const config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      };

      const childrenListMap = {};
      const nodeMap = {};
      const result = [];

      data.forEach((item) => {
        const parentId = item[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeMap[item[config.id]] = item;
        childrenListMap[parentId].push(item);
      });

      data.forEach((item) => {
        const parentId = item[config.parentId];
        if (!nodeMap[parentId]) {
          result.push(item);
        }
      });

      const handleChildren = (children) => {
        if (!children) return;
        children.forEach((item) => {
          item[config.childrenList] = childrenListMap[item[config.id]];
          if (item[config.childrenList]) {
            handleChildren(item[config.childrenList]);
          }
        });
      };

      handleChildren(result);
      return result;
    },
    // 筛选节点
    filterNode(value, data) {
      // console.log(4, value, data);
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // console.log(999, data)
      this.course_value = data.name;
      this.courseId = data.id;

      this.$emit("search", data, data.parentId);
      // console.log("树节点筛查", this.course_value);
    },
  },
};
</script>

<style>
/* // 禁止旋转 */
.el-tree .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

/* //有子节点 且未展开 */
.el-tree .el-icon-caret-right:before {
  /* //这里是你需要修改的图标路径 */
  background: url("../../assets/images/shouqi.svg") no-repeat 0 0;
  content: "";
  display: block;
  width: 14px;
  height: 14px;
  font-size: 14px;
  background-size: 14px;
}

/* //有子节点 且已展开 */
.el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  background: url("../../assets/images/zhankai.svg") no-repeat 0 0;
  content: "";
  display: block;
  width: 14px;
  height: 14px;
  font-size: 14px;
  background-size: 14px;
}

/* // 无子节点 */
.el-tree .el-tree-node__expand-icon.is-leaf::before {
  background: url("../../assets/images/zhankai.svg") no-repeat 0 0;
  content: "";
  display: block;
  width: 14px;
  height: 14px;
  font-size: 14px;
  background-size: 14px;
}
</style>
